﻿#region

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using Infrastructure;

#endregion

namespace SubsDownloader.Core.Providers.OpenSubtitles
{
    public class MovieFile
    {
        public byte[] cover { get; set; }
        public string hash { get; set; }
        public string filename { get; set; }
        public string originalfilename { get; set; }
        public string originalfolder { get; set; }
        public SubRes subRes { get; set; }
        public byte[] subtitle { get; set; }
        public string subtitleId { get; set; }
        public string oldSubtitle { get; set; }
        public Imdbdata imdbinfo { get; set; }
        public string oldSubtitleLang { get; set; }

        public string GetSubtitleFileName()
        {
            return Path.GetDirectoryName( filename ) + "\\" + Path.GetFileNameWithoutExtension( filename ) + "." +
                   subRes.ISO639 + "." + subRes.SubFormat;
        }

        public string GetName()
        {
            return Path.GetFileNameWithoutExtension( filename );
        }

        public void saveSubtitle( bool overwrite )
        {
            string filenameToWrite = GetSubtitleFileName();
            if ( File.Exists( filenameToWrite ) )
            {
                if ( overwrite )
                {
                    File.Delete( filenameToWrite );
                }
                else
                {
                    return;
                }
            }
            var fStream = new FileStream( GetSubtitleFileName(), FileMode.CreateNew );

            var bw = new BinaryWriter( fStream );

            bw.Write( subtitle );

            bw.Close();

            fStream.Close();
        }

        public void GetOldSubtitle( List<string> subtitleFormats, List<LangMap> theLangMap, string langSeq )
        {
            var langSeqSplit = new List<string>( langSeq.Split( ',' ) );
            var myf = new FileInfo( filename );
            string[] theFiles = Directory.GetFiles( myf.DirectoryName,
                                                    Path.GetFileNameWithoutExtension( filename ) + ".*" );

            string bestOldSubFile = "";
            string bestOldSubFileLang = "";

            foreach ( var file in theFiles )
            {
                if ( file == filename )
                {
                    continue;
                }
                string ext = Path.GetExtension( file );
                if ( subtitleFormats.Contains( ext.Replace( ".", "" ) ) )
                {
                    if ( (langSeqSplit.Count == 1) || (langSeqSplit.Contains( "el" ) && (langSeqSplit.Count == 2)) )
                    {
                        if ( file.Contains( langSeqSplit[0] ) )
                        {
                            bestOldSubFile = file;
                        }
                    }
                    else
                    {
                        string l = OpenSubtitlesUtils.ParseLangCodeFromFile( file, theLangMap );
                        if ( bestOldSubFile == "" )
                        {
                            bestOldSubFile = file;
                            if ( l != "" )
                            {
                                bestOldSubFileLang = l;
                            }
                            continue;
                        }
                        if ( (l != "") && (langSeqSplit.IndexOf( l ) != -1) )
                        {
                            if ( bestOldSubFileLang == "" )
                            {
                                bestOldSubFileLang = l;
                                bestOldSubFile = file;
                                continue;
                            }
                            if ( langSeqSplit.IndexOf( l ) < langSeqSplit.IndexOf( bestOldSubFileLang ) )
                            {
                                bestOldSubFile = file;
                                bestOldSubFileLang = l;
                            }
                        }
                    }
                }
            }
            oldSubtitle = bestOldSubFile;
            oldSubtitleLang = bestOldSubFileLang;

            if ( (langSeqSplit.Count == 1) || (langSeqSplit.Contains( "el" ) && (langSeqSplit.Count == 2)) )
            {
                if ( !oldSubtitle.Contains( langSeqSplit[0] ) )
                {
                    oldSubtitle = "";
                    oldSubtitleLang = "";
                }
            }
        }

        public bool SelectBestSubtitle( BindingList<SubRes> subs, List<string> ls )
        {
            SubRes best = null;
            foreach ( var tr in subs )
            {
                if ( hash == tr.MovieHash )
                {
                    if ( best == null )
                    {
                        best = tr;
                        continue;
                    }
                    if ( ls.IndexOf( tr.SubLanguageID ) < ls.IndexOf( best.SubLanguageID ) )
                    {
                        best = tr;
                    }
                }
            }
            if ( best != null )
            {
                foreach ( var tr in subs )
                {
                    if ( hash == tr.MovieHash )
                    {
                        if ( best.SubLanguageID == tr.SubLanguageID )
                        {
                            try
                            {
                                if ( float.Parse( tr.SubRating ) > float.Parse( best.SubRating ) )
                                {
                                    best = tr;
                                }
                            }
                            catch ( Exception ex )
                            {
                            }
                        }
                    }
                }
            }
            if ( best != null )
            {
                subtitleId = best.IDSubtitleFile;
                subRes = best;
                return true;
            }
            return false;
        }

        public void rename( string FileFormat, string CDFormat )
        {
            if ( subRes != null )
            {
                string cdStr = "";
                if ( subRes.SubActualCD == "1" )
                {
                    if ( subRes.SubSumCD != "1" )
                    {
                        cdStr = CDFormat.Replace( "%C", "1" );
                    }
                }
                else if ( subRes.SubActualCD != "" )
                {
                    cdStr = CDFormat.Replace( "%C", subRes.SubActualCD );
                }

                //                }
                /*                if (subRes.SubActualCD == "1")
                                {
                                    if (subRes.SubSumCD != "1")
                                    {
                                        cdStr = "-CD1";
                                    }
                                }
                                else if (subRes.SubActualCD != "")
                                {
                                    cdStr = "-CD" + subRes.SubActualCD;
                                }*/

                if ( subRes.MovieName != "" )
                {
                    string newName = Path.GetDirectoryName( filename ) + "\\" + FileFormat +
                                     Path.GetExtension( filename );
                    newName = newName.Replace( "%M", OpenSubtitlesUtils.FilenameFromTitle( subRes.MovieName ) );
                    newName = newName.Replace( "%Y", subRes.MovieYear );
                    newName = newName.Replace( "%C", cdStr );
                    //                    string newName = Path.GetDirectoryName(filename) + "\\" + FilenameFromTitle(subRes.MovieName) + "(" + subRes.MovieYear + ")" + cdStr + Path.GetExtension(filename);
                    if ( !File.Exists( newName ) )
                    {
                        try
                        {
                            File.Move( filename, newName );
                            originalfilename = Path.GetFileName( filename );
                            filename = newName;
                        }
                        catch ( Exception ex )
                        {
                            Console.WriteLine( "Error renaming movie: " + filename + "\n" + ex.Message );
                        }
                    }
                }
            }
        }

        public void newFolder( string rootFolder, string FolderFormat )
        {
            if ( subRes != null )
            {
                if ( subRes.MovieName != "" )
                {
                    string newName = rootFolder + "\\" + FolderFormat;
                    newName = newName.Replace( "%M", OpenSubtitlesUtils.FilenameFromTitle( subRes.MovieName ) );
                    newName = newName.Replace( "%Y", subRes.MovieYear );
                    if ( !Directory.Exists( newName ) )
                    {
                        try
                        {
                            Directory.CreateDirectory( newName );
                        }
                        catch ( Exception ex )
                        {
                            Console.WriteLine( "Could not create directory: " + filename + "\n" + ex.Message );
                        }
                    }
                    if ( Path.GetDirectoryName( filename ) != newName )
                    {
                        try
                        {
                            originalfolder = Path.GetDirectoryName( filename );
                            File.Move( filename, newName + "\\" + Path.GetFileName( filename ) );
                            filename = newName + "\\" + Path.GetFileName( filename );
                        }
                        catch ( Exception ex )
                        {
                            Console.WriteLine( "Could not move file to new directory: " + filename + "\n" + ex.Message );
                        }
                    }
                }
            }
        }

        public void saveNfo()
        {
            try
            {
                if ( subRes != null )
                {
                    var lstNfo = new List<string>();
                    lstNfo.Add( "Name: " + subRes.MovieName );
                    lstNfo.Add( "Year: " + subRes.MovieYear );
                    lstNfo.Add( "URL: " + "http://www.imdb.com/title/tt0" + subRes.IDMovieImdb );
                    lstNfo.Add( "Rating: " + subRes.MovieImdbRating );
                    if ( imdbinfo != null )
                    {
                        addCSV( "Directors", imdbinfo.directors.Values, lstNfo );
                        addCSV( "Cast", imdbinfo.cast.Values, lstNfo );
                        addCSV( "Genres", imdbinfo.genres, lstNfo );
                        addString( "Duration", imdbinfo.duration, lstNfo );
                        addString( "Plot", imdbinfo.plot, lstNfo );
                        addCSV( "Languages", imdbinfo.language, lstNfo );
                        addCSV( "Countries", imdbinfo.country, lstNfo );
                        addCSV( "Aka", imdbinfo.aka, lstNfo );
                        addCSV( "Writers", imdbinfo.writers.Values, lstNfo );
                        addString( "Tagline", imdbinfo.tagline, lstNfo );
                        addString( "Goofs", imdbinfo.goofs, lstNfo );
                        addString( "Trivia", imdbinfo.trivia, lstNfo );
                        addCSV( "Certification", imdbinfo.certification, lstNfo );
                    }
                    if ( (originalfilename != null) && (originalfilename != filename) )
                    {
                        lstNfo.Add( "OriginalFile: " + originalfilename );
                    }
                    if ( (originalfolder != null) && (originalfolder != Path.GetDirectoryName( filename )) )
                    {
                        lstNfo.Add( "OriginalFolder: " + originalfolder );
                    }
                    lstNfo.Add( "ImdbID: " + subRes.IDMovieImdb );
                    lstNfo.Add( "Hash: " + subRes.MovieHash );
                    lstNfo.Add( "Release: " + subRes.MovieReleaseName );
                    lstNfo.Add( "CD: " + subRes.SubActualCD + "/" + subRes.SubSumCD );
                    lstNfo.Add( "SubtitleUsed: " + subRes.ZipDownloadLink );
                    lstNfo.Add( "SubtitleHash: " + subRes.SubHash );
                    string nfoFileName = Path.GetDirectoryName( filename ) + "\\" +
                                         Path.GetFileNameWithoutExtension( filename ) + ".nfo";
                    if ( File.Exists( nfoFileName ) )
                    {
                        File.Delete( nfoFileName );
                    }
                    using ( StreamWriter writer = File.AppendText( nfoFileName ) )
                    {
                        foreach ( var line in lstNfo )
                        {
                            writer.WriteLine( line );
                        }
                    }
                }
            }
            catch ( Exception ex )
            {
                Console.WriteLine( "Error writing Nfo file: " + filename + "\n" + ex.Message );
            }
        }

        private void addString( string Title, string Value, List<string> lstNfo )
        {
            if ( (Value != null) && (Value != "") )
            {
                lstNfo.Add( Title + ": " + Value );
            }
        }

        private string addCSV( string title, ICollection array, List<string> lstNfo )
        {
            string s = "";
            if ( array != null )
            {
                foreach ( string a in array )
                {
                    s = s + "," + a;
                }
                s = s.Substring( 1 );
                lstNfo.Add( title + ": " + s );
            }
            return s;
        }

        private string addCSV( string title, string[] array, List<string> lstNfo )
        {
            string s = "";
            if ( array != null )
            {
                foreach ( var a in array )
                {
                    s = s + "," + a;
                }
                s = s.Substring( 1 );
                lstNfo.Add( title + ": " + s );
            }
            return s;
        }
    }
}